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

时间:2014-06-13 14:41:49

标签: linux awk sed

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

/home/test/gp/fish/lib/fish.eye
/home/test/gp/fish/kerf/pl/teeth.eye

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

cp fish.eye /home/test/gp/fish/lib/fish.eye
cp teeth.eye /home/test/gp/fish/kerf/pl/teeth.eye

任何帮助非常感谢

感谢。

4 个答案:

答案 0 :(得分: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

它将/设置为字段分隔符,以便文件名是最后一个字段。然后是相应的打印问题。

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

awk -F/ '{printf "cp \"%s\" \"%s\"\n", $NF, $0}' your_file

在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

basename会从文件名中返回条带和后缀,因此您可以从/path/like/this.sh这样的名称获得this.sh

答案 1 :(得分:3)

通过GNU sed

$ sed -r 's/^.*\/(.*)$/cp \1 &/' file
cp fish.eye /home/test/gp/fish/lib/fish.eye
cp teeth.eye /home/test/gp/fish/kerf/pl/teeth.eye

获取最后/个符号后的文本并将其存储到组中。再次在替换部分中,“cp group wholeline”有助于提供上述输出。

答案 2 :(得分:2)

使用bash parameter substitution

while read -r line; do
    echo "cp ${line##*/} $line" 
done < file
cp fish.eye /home/test/gp/fish/lib/fish.eye
cp teeth.eye /home/test/gp/fish/kerf/pl/teeth.eye

从链接:

${parameter##word} 

The word is expanded to produce a pattern just as in filename expansion 
(see Filename Expansion). If the pattern matches the beginning of the expanded value 
of parameter, then the result of the expansion is the expanded value of parameter 
with the shortest matching pattern (the ‘#’ case) or the longest matching pattern 
(the ‘##’ case) deleted.

答案 3 :(得分:2)

这三个sed单行应该也可以工作,但awk会更直接:

sed 's/.*/& &/;s#[^ ]*/#cp #' file

sed 'h;s#.*/#cp #;G;s/\n/ /' file

sed 's#.*/\(.*\)#cp \1 &#' file
相关问题