[英]How do I swap two strings using the sed command with the delimiter being a comma?
這是我第一次在這里發帖,如果格式很奇怪,我深表歉意。
使用 sed 命令,我想將 x 和 y 從 x,y 交換為 y,x 並將交換的版本存儲到單獨的文件中。
我應該修改的文件包含,
#######bank info########
#
####name#### ####age####
#
Bob,Stevenson 27
David,Tan 43
Robert,Jackson 39
我想將名字從名字,姓氏更改為姓氏,名字。
我已經嘗試過使用該命令,
sed -e "s/^\([^#]*\) *\([,]*\)/\2\1/g" file > xxx
然而,當我檢查“交換”文件時,它看起來沒有任何改變。 為什么?
預期的 output 為:
#######bank info########
#
####name#### ####age####
#
Stevenson,Bob 27
Tan,David 43
Jackson,Robert 39
但我的 output 是:
#######bank info########
#
####name#### ####age####
#
Bob,Stevenson 27
David,Tan 43
Robert,Jackson 39
這與初始版本完全相同。 為什么會這樣?
sed '
# only lines that do not start with a #
/^#/!{
# match from the start
# match up until a comma
# then match the comma
# then match up until a space
# swap the part before the comma and after comma
s/^\([^,]*\),\([^ ]*\)/\2,\1/
}
'
還有更短的版本:
sed '/^#/!s/^\([^,]*\),\([^ ]*\)/\2,\1/'
與@KamilCuk 的非常好的答案相同的方法,但使用擴展的正則表達式和單詞字符,你可以做
sed -E '/,/s/(\w+),(\w+)/\2,\1/' file > newfile
其中/,/
僅在帶有','
的行上運行,並且(\w+)
的捕獲組匹配一個或多個單詞字符的組。 (\w+),(\w+)
表達式確保有兩組由逗號分隔的單詞字符,然后\2,\1
只需以相反的順序重新插入反向引用,例如
示例使用/輸出
$ sed -E '/,/s/(\w+),(\w+)/\2,\1/' file
#######bank info########
#
####name#### ####age####
#
Stevenson,Bob 27
Tan,David 43
Jackson,Robert 39
如果您可以使用awk
,就可以了。
awk -F'[ ,]+' '/,/{$0=$2","$1"\t"$3}1' file
#######bank info########
#
####name#### ####age####
#
Stevenson,Bob 27
Tan,David 43
Jackson,Robert 39
與awk
相比, sed
可能更容易理解 :)
-F'[,]+'
用一個或多個逗號或空格分隔行/,/
對於帶逗號的行:$0=$2","$1"\t"$3
用逗號和制表符以新順序重建行1
始終為真,執行默認操作,打印該行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.