将第一列内容和前缀附加到行尾

问题描述 投票:0回答:2

我正在尝试将列内容附加到每行的末尾。例如,我有:

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

添加“I”很容易添加:sed 's/$/I/'文件,但我遇到复制和附加第一列内容的问题

linux bash sed
2个回答
1
投票

尝试:

$ 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

Compatibility

以上应适用于所有现代sed。对于较旧的GNU sed,用-E替换-r

sed -r 's/([[:digit:]]+),.*/& I\1/' file

0
投票
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 I2
© www.soinside.com 2019 - 2024. All rights reserved.