在包含正斜杠的文件中使用awk

0 linux awk sed

我有一个包含类似行的文件...

/home/test/gp/fish/lib/fish.eye
/home/test/gp/fish/kerf/pl/teeth.eye
Run Code Online (Sandbox Code Playgroud)

我想把每一行末尾的最后一个字符串放在行的开头,例如..

cp fish.eye /home/test/gp/fish/lib/fish.eye
cp teeth.eye /home/test/gp/fish/kerf/pl/teeth.eye
Run Code Online (Sandbox Code Playgroud)

任何帮助非常感谢

谢谢.

fed*_*qui 6

以此为例:

$ awk -F/ '{print "cp", $NF, $0}' your_file
cp fish.eye /home/test/gp/fish/lib/fish.eye
cp teeth.eye /home/test/gp/fish/kerf/pl/teeth.eye
Run Code Online (Sandbox Code Playgroud)

它设置/为字段分隔符,因此文件名是最后一个字段.然后是相应的打印问题.

或者更安全,处理带有空格和globbing字符等的文件名(感谢Ed Morton!):

awk -F/ '{printf "cp \"%s\" \"%s\"\n", $NF, $0}' your_file
Run Code Online (Sandbox Code Playgroud)

在bash中,您可以遍历这些行并使用basename:

while IFS= read -r line
do
    echo "cp" "$(basename "$line")" "$line"
    #printf "cp %s %s\n" "$(basename "$line")" "$line" <-- this also works
done < your_file
Run Code Online (Sandbox Code Playgroud)

basename从文件名中返回条带和后缀,以便从/path/like/this.sh您获得的名称中返回this.sh.