在这种情况下如何使用shell,bash或sed命令

时间:2014-08-07 17:59:36

标签: linux bash shell awk sed

我有这个文件

name1
name2
name3

以及如何实现这一结果:

first
user:name1
end

first
user:name2
end

first
user:name3
end

我可以使用sed 's#^#user:#'来实现

user:name1
user:name2
user:name3

但仍然没有完成这项工作。任何人都帮助我。谢谢

5 个答案:

答案 0 :(得分:6)

添加普通bash版本:

while read line; do echo -e "first\nuser:$line\nend\n"; done < names.txt

答案 1 :(得分:5)

您可以使用任意数量的工具轻松完成此操作。想到了Awk:

awk '{ print "first";
    print "user:", $0;
    print "end";
    print "" }' "$file"

答案 2 :(得分:2)

awk '{printf "first\nuser:%s\nend\n\n", $0}' file

答案 3 :(得分:1)

例如,您有一个文件1.txt:

$ cat 1.txt

name1
name2
name3
shenzi

$ sed&#34; s /^(.*)$/ first \ nuser:\ 1 \ nend \ n /&#34;的1.txt

first
user:name1
end

first
user:name2
end

first
user:name3
end

first
user:shenzi
end

答案 4 :(得分:0)

sed 's#^\(.*\)$#first\nuser:\1\nend\n#' filename 

\( .. \)-将括号之间的匹配字符串存储到\1中,然后仅创建所需的字符串。