Extract specific strings from line in file and output to another file with modifications

笑着哭i 提交于 2019-12-23 16:42:53

问题


New to linux and trying to escape doing this the hard way. I have a file ("output.txt") that contains the results of a 'find' command. Example first three lines from "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

I'd like to use awk or sed (or similar) to extract two parts from the path listed for each line, and output to a new file ("run.txt") with extra information added on each line like so:

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

I'm guessing this might also involve something like "cut", but I can't get my head wrapped around how to account for changing folder and file names.

Any help would be much appreciated.


回答1:


sed 's|^|cd |; s|/\([^/]*\)$|; $RUNLD \1|' inputfile > run

It says:

  • insert "cd " at the beginning of the line
  • for the last slash and what comes after, substitute "; $RUNLD " and the final part (captured by the parentheses)



回答2:


sed -e 's/^/cd /; s|/\([^/]*\)$|; \$RUNLD \1|' file

This prepends "cd " and replaces the last / with "; $RUNLD ". Voila!




回答3:


Just with bash

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

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




回答4:


I'd probably go about this with a loop based grep solution since I don't know cut, or awk very well haha. This does the trick:

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:


This might work for you:

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


来源:https://stackoverflow.com/questions/10487531/extract-specific-strings-from-line-in-file-and-output-to-another-file-with-modif

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!