我尝试将列内容附加到每行的末尾。例如,我有:
0,John L Doe,Street,City
1,Jane L Doe,Street,City
2,John L Doe,Street,City
3,John L Doe,Street,City
4,Jane L Doe,Street,City
5,John L Doe,Street,City
6,John L Doe,Street,City
7,Jane L Doe,Street,City尝试将由逗号分隔的第一列附加到包含字符"I“的每一行的末尾,使其变为:
0,John L Doe,Street,City I0
1,Jane L Doe,Street,City I1
2,John L Doe,Street,City I2
3,John L Doe,Street,City I3
4,Jane L Doe,Street,City I4
5,John L Doe,Street,City I5
6,John L Doe,Street,City I6
7,Jane L Doe,Street,City I7使用:sed 's/$/I/'文件添加"I“很容易,但是我在复制和附加第一列内容时遇到了问题
发布于 2018-03-04 12:32:31
尝试:
$ sed -E 's/([[:digit:]]+),.*$/& I\1/' file
0,John L Doe,Street,City I0
1,Jane L Doe,Street,City I1
2,John L Doe,Street,City I2
3,John L Doe,Street,City I3
4,Jane L Doe,Street,City I4
5,John L Doe,Street,City I5
6,John L Doe,Street,City I6
7,Jane L Doe,Street,City I7正则表达式([[:digit:]]+),.*$从行上的第一个数字匹配到行尾。表达式([[:digit:]]+)匹配第一个逗号之前的所有数字,并将它们保存在组1中。替换文本为& I\1,其中sed将&替换为整个匹配,并将\1替换为组1。
-E选项告诉sed使用扩展正则表达式(ERE),而不是默认的基本正则表达式(BRE)。
实际上,不需要在行尾匹配的$。因为sed正则表达式总是最左边最长的匹配,所以我们的正则表达式总是匹配到行尾。因此,我们可以使用稍微简单一点的:
sed -E 's/([[:digit:]]+),.*/& I\1/' file兼容性
以上内容应该可以在所有现代sed上运行。对于较旧的GNU sed,请用-r替换-E
sed -r 's/([[:digit:]]+),.*/& I\1/' file发布于 2018-03-04 15:17:36
Try this:
$ cat file.sh
0,John L Doe,Street,City
1,Jane L Doe,Street,City
2,John L Doe,Street,City
$ cat example.sh
while IFS=, read -r ID name street city; do
printf '%s,%s,%s,%s, %s\n' "${ID}" "${name}" "${street}" "${city}" "I${ID}"
done < "$filelocation"
$ sh example.sh
0,John L Doe,Street,City, I0
1,Jane L Doe,Street,City, I1
2,John L Doe,Street,City, I2
Another solution is:
$ cat file.sh
0,John L Doe,Street,City
1,Jane L Doe,Street,City
2,John L Doe,Street,City
$ cat example.sh
IFS='
'
for line in $(cat file.sh)
do
echo ${line/%/ I${line%,*,*,*}}
done
$ sh example.sh
0,John L Doe,Street,City I0
1,Jane L Doe,Street,City I1
2,John L Doe,Street,City I2https://stackoverflow.com/questions/49091894
复制相似问题