![](/img/trans.png)
[英]Forcing a Linux Sort to Treat a Record With Spaces as a Single Data Column
[英]Treat spaces as spaces after n column
如何運行 bash column
命令,在 n 列之后將空格視為空格而不是分隔符?
輸入:
field1 field2 field3 field 4 with spaces
foo1 foo2 foo3 foo4
bar1 bar2 bar3 bar 4 with spaces
Output:
col1 col2 col3 col4
field1 field2 field3 field 4 with spaces
foo1 foo2 foo3 foo4
bar1 bar2 bar3 bar 4 with spaces
也許在column
命令之前用其他字符替換空格,然后再用空格替換它? awk
或sed
可能是正確的工具,但我對它們不太熟悉。
任何幫助表示贊賞,請。 別打我。 這是我在這里的第一個問題......
這個怎么樣
$ cat t
field1 field2 field3 field 4 with spaces
foo1 foo2 foo3 foo4
bar1 bar2 bar3 bar 4 with spaces
$ cat t | sed -E 's/^([^ ]+) ([^ ]+) ([^ ]+) (.+)$/\1\t\2\t\3\t\4/g'
field1 field2 field3 field 4 with spaces
foo1 foo2 foo3 foo4
bar1 bar2 bar3 bar 4 with spaces
$
另一個用制表符替換前 3 個空格的 awk:
awk '{for (i=1; i<=3; ++i) sub(/ +/, "\t")} 1' file
field1 field2 field3 field 4 with spaces
foo1 foo2 foo3 foo4
bar1 bar2 bar3 bar 4 with spaces
如何構建另一個變量,這里s4
會引起混淆:
$ awk '
BEGIN {
OFS="\t"
}
{
for(i=4;i<=NF;i++)
s4=s4 (s4==""?"":" ") $i
print $1,$2,$3,s4
s4=""
}' file
Output:
field1 field2 field3 field 4 with spaces
foo1 foo2 foo3
bar1 bar2 bar3 bar 4 with spaces
如果有多個like this
的空格,需要設置FS=" "
。
使用 awk 和文件“空格”中的示例數據,同時仍然使用列:
awk '{ printf $1":"$2":"$3":";
for (i=4;i<=NF;i++)
{ if (i != NF) { printf $i" "
}
else { printf $i
}
}
printf "\n"
}' spaces | column -t -s":"
使用 awk 使用“:”分隔前四個字段,然后使用“:”作為分隔符使用 pipe 到列。
這可能對你有用(GNU sed):
sed 'y/ /\t/;s/\t/ /4g' file
將所有空格轉換為制表符,然后將第 4 個制表符和之后的制表符替換為空格。
如果您更喜歡一種對稱性:
sed 's/ /\t/g;s/\t/ /4g' file
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.