我有以下几行
3, 3, 100
4, 2, 50
8, 5, 80
.
.
.
我想要以下输出
line starts at 3 and ends at 3 with value 100
line starts at 4 and ends at 2 with value 50
line starts at 8 and ends at 5 with value 80
.
.
.
我尝试了以下操作:sed 's/^/line starts at /'
然后将此命令应用于输出:sed 's/, / and ends at /'
然后将此命令应用于输出sed 's/, / with value /'
。有什么办法可以在一行中完成吗?
答案1
awk
对于这种格式化输入 - 格式化输出很有用:
awk -F, '{printf("line starts at %d and ends at %d with value %d\n", $1, $2, $3)}' file
line starts at 3 and ends at 3 with value 100
line starts at 4 and ends at 2 with value 50
line starts at 8 and ends at 5 with value 80
答案2
一个 shellwhile read
循环printf
:
while IFS=', ' read c1 c2 c3; do
printf 'line starts at %s and ends at %s with value %s\n' \
"$c1" "$c2" "$c3"
done <file
通过将IFS
变量设置为空格和逗号,该read
命令将使用这些字符作为字段分隔符。
输出:
line starts at 3 and ends at 3 with value 100
line starts at 4 and ends at 2 with value 50
line starts at 8 and ends at 5 with value 80
答案3
原来sed中有-e选项
sed -e 's/^/line starts at /g' -e 's/, / and ends at /' -e 's/, / with value at /'
答案4
在 shell 本身中有一种简单快捷的方法可以做到这一点:-
# cat f
3, 3, 100
4, 2, 50
8, 5, 80
# cat f | while read line ; do IFS=", " array=($line) ; echo "line starts at ${array[0]} and ends at ${array[1]} with value ${array[2]}"; done
line starts at 3 and ends at 3 with value 100
line starts at 4 and ends at 2 with value 50
line starts at 8 and ends at 5 with value 80