Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 从文件中的行中提取特定字符串,并在修改后输出到另一个文件_Bash_Sed_Awk_Find_Cut - Fatal编程技术网

Bash 从文件中的行中提取特定字符串,并在修改后输出到另一个文件

Bash 从文件中的行中提取特定字符串,并在修改后输出到另一个文件,bash,sed,awk,find,cut,Bash,Sed,Awk,Find,Cut,刚接触linux,并试图逃避这种艰难的做法。我有一个文件(“output.txt”),其中包含“find”命令的结果。“output.txt”的前三行示例: 我想使用awk或sed(或类似工具)从每行列出的路径中提取两部分,并输出到一个新文件(“run.txt”),在每行添加额外信息,如下所示: cd /home/user/temp/LT50150292009260GNC01; $RUNLD L5015029_02920090917_MTL.txt cd /home/user/temp/LT50

刚接触linux,并试图逃避这种艰难的做法。我有一个文件(“output.txt”),其中包含“find”命令的结果。“output.txt”的前三行示例:

我想使用awk或sed(或类似工具)从每行列出的路径中提取两部分,并输出到一个新文件(“run.txt”),在每行添加额外信息,如下所示:

cd /home/user/temp/LT50150292009260GNC01; $RUNLD L5015029_02920090917_MTL.txt
cd /home/user/temp/LT50150292009276GNC01; $RUNLD L5015029_02920091003_MTL.txt
cd /home/user/temp/LT50150292009292GNC01; $RUNLD L5015029_02920091019_MTL.txt
我猜这可能还包括“剪切”之类的内容,但我不知道如何解释更改文件夹和文件名


任何帮助都将不胜感激。

我可能会使用基于循环的grep解决方案,因为我不太清楚
cut
,或者
awk
,哈哈。这就是诀窍:

while read x; do folder=$(echo "$x" | grep -o '^.*/'); file=$(echo "$x" | grep -o '[^/]*$'); echo "cd ${folder:0:-1}; \$RUNLD $file"; done < output.txt > run
读取x时
;do folder=$(echo“$x”| grep-o'^.*/');文件=$(echo“$x”| grep-o'[^/]*$”;echo“cd${文件夹:0:-1};\$RUNLD$file”;完成运行
它说:

  • 在行首插入“cd”
  • 对于最后一个斜杠和后面的内容,替换“$RUNLD”和最后一部分(用括号括起来)
这将在“cd”前面加上前缀,并将最后一个/替换为“$RUNLD”。瞧

就用bash

while IFS= read -r filename; do
  printf 'cd %s; $RUNLD %s\n' "${filename%/*}" "${filename##*/}"
done < output.txt > run
而IFS=read-r文件名;做
printf'cd%s$RUNLD%s\n'${filename%/*}'${filename}##*/}
完成运行

请参见

这可能适合您:

sed 's/\(.*\)\//cd \1; $RUNLD /' file
cd /home/user/temp/LT50150292009260GNC01; $RUNLD L5015029_02920090917_MTL.txt
cd /home/user/temp/LT50150292009276GNC01; $RUNLD L5015029_02920091003_MTL.txt
cd /home/user/temp/LT50150292009292GNC01; $RUNLD L5015029_02920091019_MTL.txt

最完整的答案,尽管Jens紧随其后。谢谢Jens!虽然没有丹尼斯·威廉姆森的回答那么完整,但它确实像广告上说的那样有效。没什么大不了的。丹尼斯快了一秒钟:-)不过我还是很感激。
sed -e 's/^/cd /; s|/\([^/]*\)$|; \$RUNLD \1|' file
while IFS= read -r filename; do
  printf 'cd %s; $RUNLD %s\n' "${filename%/*}" "${filename##*/}"
done < output.txt > run
sed 's/\(.*\)\//cd \1; $RUNLD /' file
cd /home/user/temp/LT50150292009260GNC01; $RUNLD L5015029_02920090917_MTL.txt
cd /home/user/temp/LT50150292009276GNC01; $RUNLD L5015029_02920091003_MTL.txt
cd /home/user/temp/LT50150292009292GNC01; $RUNLD L5015029_02920091019_MTL.txt