【问题标题】:Bash: Parse Urls from file, process them and then remove them from the fileBash:从文件中解析 URL,处理它们,然后从文件中删除它们
【发布时间】:2017-03-14 20:03:53
【问题描述】:

我正在尝试自动化一个过程,系统将获取文件的内容(每行 1 个 Url),使用 wget 从站点(https 文件夹)中获取文件,然后从文件中删除该行。

我已经尝试了几次,但 sed 部分(最后)无法理解字符串(我尝试转义字符)并将其从该文件中删除!

cat File
https://something.net/xxx/data/Folder1/
https://something.net/xxx/data/Folder2/
https://something.net/xxx/data/Folder3/

我的代码行是:

cat File | xargs -n1 -I @ bash -c 'wget -r -nd -l 1 -c -A rar,zip,7z,txt,jpg,iso,sfv,md5,pdf --no-parent --restrict-file-names=nocontrol --user=test --password=pass --no-check-certificate "@" -P /mnt/USB/ && sed -e 's|@||g' File'

直到sed -e 's|@||g' File 部分..

提前致谢!

【问题讨论】:

  • 如果您要阅读整个文件,为什么要逐行删除其内容?你就不能data=$(cat File); echo -n > File 吗?
  • 对于更高级的情况,您可能需要考虑使用flock

标签: bash parsing sed xargs


【解决方案1】:

如果可能,请不要使用 cat。这是不好的做法,可能是大文件的问题......你可以改变

cat File | xargs -n1 -I @ bash -c 

for siteUrl in $( < "File" ); do

使用带双引号的 sed 更正确、更简单...我的变体:

scriptDir=$( dirname -- "$0" )
for siteUrl in $( < "$scriptDir/File.txt" )
do
    if [[ -z "$siteUrl" ]]; then break; fi # break line if him empty
    wget -r -nd -l 1 -c -A rar,zip,7z,txt,jpg,iso,sfv,md5,pdf --no-parent --restrict-file-names=nocontrol --user=test --password=pass --no-check-certificate "$siteUrl" -P /mnt/USB/ && sed -i "s|$siteUrl||g" "$scriptDir/File.txt"
done

【讨论】:

  • 感谢您的回复!我怎样才能让它更新文件本身?我用 4 行测试它(3 行无效,1 行有效)。我在屏幕上获得了所需的输出(4 行之间有间隙,有效的缺失)但文件保持不变..
  • 我尝试切换到sed -i "|$siteUrl|d",但得到sed: -e expression #1, char 1: unknown command: |'`。
  • 还有另一个问题,当 URL 包含空格时,此代码会将其分解为不同的元素..
  • 对不起,我不测试代码和快速改变你的行。对于更新文件,需要使用-i 进行 sed。使用sed -i "s|$siteUrl||g"sed -i "\|$siteUrl|d" 可以给我1个问题URL进行测试吗?
【解决方案2】:

@beliy 的答案看起来不错!

如果你想要单线,你可以这样做:

while read -r line; do \
wget -r -nd -l 1 -c -A rar,zip,7z,txt,jpg,iso,sfv,md5,pdf \
--no-parent --restrict-file-names=nocontrol --user=test \
--password=pass --no-check-certificate "$line" -P /mnt/USB/ \
&& sed -i -e '\|'"$line"'|d' "File.txt"; \
done < File.txt

编辑: You need to add a \ in front of the first pipe

【讨论】:

  • 感谢您的回复!完成后它需要额外的空间。我运行它,当它到达 sed 部分时,它尝试下载我添加的测试位置(3 个错误和 1 个好):sed: -e expression #1, char 1 :未知命令:`|'
  • 好点,你需要` in front of the first |` 显然,我不知道!谢谢!
  • 正确,如果您更改 sed -e with sed -i,这正是我正在寻找的 ;)
【解决方案3】:

我相信您只需要在sed -e 之后使用双引号即可。而不是:

'...&& sed -e 's|@||g' File'

你需要

'...&& sed -e '"'s|@||g'"' File'

【讨论】:

  • 感谢您的回复!双引号有效(它曾经通过错误)。
  • 我正在尝试将其更改为sed -i '"'|@|d'"',但无法使其正常工作。你有什么想法吗??
【解决方案4】:

我明白你想做什么,但我不理解 sed 命令,包括管道。也许是一些我不明白的花哨的格式。

反正我觉得sed命令应该是这样的……

sed -e 's/@//g'

此命令将从流中删除所有 @。
我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    相关资源
    最近更新 更多