我試圖刪除前導及以下input.txt
中的第2列尾隨空格從後面的空格:修剪領導和AWK
Name, Order
Trim, working
cat,cat1
我已經使用了低於awk
刪除第二列中的前導空格和尾部空格,但它不起作用。我錯過了什麼?
awk -F, '{$2=$2};1' input.txt
這使輸出爲:
Name, Order
Trim, working
cat,cat1
首尾空格不會被刪除。
我試圖刪除前導及以下input.txt
中的第2列尾隨空格從後面的空格:修剪領導和AWK
Name, Order
Trim, working
cat,cat1
我已經使用了低於awk
刪除第二列中的前導空格和尾部空格,但它不起作用。我錯過了什麼?
awk -F, '{$2=$2};1' input.txt
這使輸出爲:
Name, Order
Trim, working
cat,cat1
首尾空格不會被刪除。
如果要修剪所有空格,只有在有一個逗號線,並使用awk
,那麼下面就爲你工作:
awk -F, '/,/{gsub(/ /, "", $0); print} ' input.txt
如果你只是想刪除第二列空間中,表達改變
awk -F, '/,/{gsub(/ /, "", $2); print$1","$2} ' input.txt
注意gsub
替換的字符在//
與第二表達,在作爲第三個參數的變量 - 並且這樣做in-place
- 在鄰其他詞,當它完成時,$0
(或$2
)已被修改。
充分說明:
-F, use comma as field separator
(so the thing before the first comma is $1, etc)
/,/ operate only on lines with a comma
(this means empty lines are skipped)
gsub(a,b,c) match the regular expression a, replace it with b,
and do all this with the contents of c
print$1","$2 print the contents of field 1, a comma, then field 2
input.txt use input.txt as the source of lines to process
編輯我想指出的是,@寶馬的解決方案是更好,因爲它實際上只修剪領先,並連續兩次gsub
命令尾隨空格。在給予學分的同時,我會解釋它是如何工作的。
gsub(/^[ \t]+/,"",$2); - starting at the beginning (^) replace all (+ = zero or more, greedy)
consecutive tabs and spaces with an empty string
gsub(/[ \t]+$/,"",$2)} - do the same, but now for all space up to the end of string ($)
1 - ="true". Shorthand for "use default action", which is print $0
- that is, print the entire (modified) line
我會用sed
:
sed 's/, /,/' input.txt
這將消除對,
領先之後的空間。 輸出:
Name,Order
Trim,working
cat,cat1
更普遍的可能是下面的,它會在,
後除去可能有多個空格和/或製表符:
sed 's/,[ \t]\?/,/g' input.txt
它也將因爲兩個以上的列上工作全球改性劑/g
@Floris在討論中提出一個解決方案,消除拖尾和和結束在每個空格科拉姆(甚至第一和最後一個),而不是在塔的中部去除空格:
sed 's/[ \t]\?,[ \t]\?/,/g; s/^[ \t]\+//g; s/[ \t]\+$//g'
IMO sed
是這個職位的最佳工具。然而,這裏配備了一個awk
解決方案,因爲你要的那種:
awk -F', ' '{printf "%s,%s\n", $1, $2}' input.txt
自帶的是要消除所有的空格,另一種簡單的解決方案是tr -d
:
cat input.txt | tr -d ' '
簡單的辦法是可能要使用tr
$ cat -A input
^I Name, ^IOrder $
Trim, working $
cat,cat1^I
$ tr -d '[:blank:]' < input | cat -A
Name,Order$
Trim,working$
cat,cat1
不錯而且緊湊。你可以修改它,所以它只修整第二列(每個問題)? – Floris
除去開頭和一個GSUB第2列
awk 'BEGIN{FS=OFS=","}{gsub(/^[ \t]+/,"",$2);gsub(/[ \t]+$/,"",$2)}1' input.txt
另一種方式結尾空白:
awk 'BEGIN{FS=OFS=","} {gsub(/^[ \t]+|[ \t]+$/, "", $2)}1' infile
以下似乎工作:
awk -F',[[:blank:]]*' '{$2=$2}1' OFS="," input.txt
如果它是安全的假設第二列僅有一組空格(這是原始示例):
awk '{print $1$2}' /tmp/input.txt
添加另一個字段,例如, awk '{print $1$2$3}' /tmp/input.txt
將捕獲兩組空格(第二列中最多三個字),如果數量較少,則不會中斷。
如果你有一個不確定的(大量)空格分隔的單詞,我會使用以前的建議之一,否則這個解決方案是使用awk最容易找到的。
我剛碰到這個。正確的答案是:
awk 'BEGIN{FS=OFS=","} {gsub(/^[[:space:]]+|[[:space:]]+$/,"",$2)} 1'
你能解釋一下嗎? – Marjer
查看@ EdMorton對單個「gsub」解決方案的回答。它也使用角色類來進行空間這是一件更好的事情。 – codeforester