我的bash
脚本仅运行sed
.我用来运行它的命令:
sed -f sedhw.bash thesbians.txt
内容sedhw.bash
s/[0-9]*//g
s/1908/---/g; s/1895/---/g; s/1903/---/g
s/,.*//g
s/^[^"]*"/"/
s/,[^",]*"/,/;s/"//g
我需要它一次运行文件中的每个命令一次,给我 5 个不同的输出而不是一个输出。
文本文件看起来像这样
Chase,Cornelius 1943 "Chevy"
Davis,Ruth 1908 "Bette"
Keaton,Joseph 1895 "Buster"
Stone,Emily 1988 "Emma"
Lee,Shelton 1957 "Spike"
Reynolds,Mary 1932 "Debbie"
Crosby,Harry 1903 "Bing"
Fey,Stamatina 1970 "Tina"
答案1
作为@roaima和@kusalananda已经评论过,你的sedhw.bash
是一个 sedfile。
sed -f sedhw.bash thesbians.txt
将针对文件 thesbians.txt 运行 sedhw.bash 中的所有 sed 命令
你想做什么反而是循环遍历 sedhw.bash 中的行并执行每一行以生成新的输出文件:
#!/bin/bash
while read num line; do
sed "$line" thesbians.txt > output.${num}.txt
done < <(nl sedhw.bash)
解释一下:
nl sedhw.bash
将为您的命令编号并“制表符分隔”行号和命令:
1 s/[0-9]*//g
2 s/1908/---/g; s/1895/---/g; s/1903/---/g
3 s/,.*//g
4 s/^[^"]*"/"/
5 s/,[^",]*"/,/;s/"//g
<(...)
将在 while 循环中将命令输出作为文件呈现。
循环将逐行输入该“文件”,<
并将制表符分隔的字段读取到变量“num”和“line”中。
sed
执行命令“$line”并将其写入以 sedhw.bash 中相应行编号的文件中。
结果
$ for item in output*; do echo; echo "=== $item ==="; cat $item ; done
=== output.1.txt ===
Chase,Cornelius "Chevy"
Davis,Ruth "Bette"
Keaton,Joseph "Buster"
Stone,Emily "Emma"
Lee,Shelton "Spike"
Reynolds,Mary "Debbie"
Crosby,Harry "Bing"
Fey,Stamatina "Tina"
=== output.2.txt ===
Chase,Cornelius 1943 "Chevy"
Davis,Ruth --- "Bette"
Keaton,Joseph --- "Buster"
Stone,Emily 1988 "Emma"
Lee,Shelton 1957 "Spike"
Reynolds,Mary 1932 "Debbie"
Crosby,Harry --- "Bing"
Fey,Stamatina 1970 "Tina"
=== output.3.txt ===
Chase
Davis
Keaton
Stone
Lee
Reynolds
Crosby
Fey
=== output.4.txt ===
"Chevy"
"Bette"
"Buster"
"Emma"
"Spike"
"Debbie"
"Bing"
"Tina"
=== output.5.txt ===
Chase,Chevy
Davis,Bette
Keaton,Buster
Stone,Emma
Lee,Spike
Reynolds,Debbie
Crosby,Bing
Fey,Tina