【问题标题】:Extract specific strings from line in file and output to another file with modifications从文件中的行中提取特定字符串并输出到另一个文件并进行修改
【发布时间】:2012-05-08 07:01:36
【问题描述】:

Linux 新手,并试图以艰难的方式逃避这种做法。我有一个文件(“output.txt”),其中包含“查找”命令的结果。示例“output.txt”中的前三行:

/home/user/temp/LT50150292009260GNC01/L5015029_02920090917_MTL.txt
/home/user/temp/LT50150292009276GNC01/L5015029_02920091003_MTL.txt
/home/user/temp/LT50150292009292GNC01/L5015029_02920091019_MTL.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

我猜这也可能涉及“剪切”之类的内容,但我无法理解如何考虑更改文件夹和文件名。

任何帮助将不胜感激。

【问题讨论】:

    标签: bash sed awk find cut


    【解决方案1】:
    sed -e 's/^/cd /; s|/\([^/]*\)$|; \$RUNLD \1|' file
    

    这会添加“cd”并将最后一个 / 替换为“; $RUNLD”。瞧!

    【讨论】:

    • 谢谢詹斯!它确实像宣传的那样有效,尽管不如丹尼斯威廉姆森的回答那么完整。
    • 没什么大不了的。丹尼斯快了一秒 :-) 点赞表示赞赏。
    【解决方案2】:

    只用 bash

    while IFS= read -r filename; do
      printf 'cd %s; $RUNLD %s\n' "${filename%/*}" "${filename##*/}"
    done < output.txt > run
    

    http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion

    【讨论】:

      【解决方案3】:
      sed 's|^|cd |; s|/\([^/]*\)$|; $RUNLD \1|' inputfile > run
      

      上面写着:

      • 在行首插入“cd”
      • 对于最后一个斜线和后面的内容,替换为“; $RUNLD”和最后一部分(由括号捕获)

      【讨论】:

      • 最完整的答案,虽然 Jens 紧随其后。
      【解决方案4】:

      我可能会使用基于循环的 grep 解决方案来解决这个问题,因为我不太了解 cutawk 哈哈。这就是诀窍:

      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
      

      【讨论】:

        【解决方案5】:

        这可能对你有用:

        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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-05
          • 2018-05-23
          • 1970-01-01
          • 2021-02-02
          相关资源
          最近更新 更多