问题描述
我有这样一行:
one:two:three:four:five:six seven:eight
,我想使用awk
来使$1
成为1,而$2
成为two:three:four:five:six seven:eight
and I want to use awk
to get $1
to be one and $2
to be two:three:four:five:six seven:eight
我知道我可以通过执行sed
来获得它.那就是先用sed
更改:
的第一个匹配项,然后使用新的定界符将其替换为awk
.
I know I can get it by doing sed
before. That is to change the first occurrence of :
with sed
then awk
it using the new delimiter.
但是用新的分隔符替换分隔符对我没有帮助,因为我不能保证新的分隔符不会在文本中出现.
However replacing the delimiter with a new one would not help me since I can not guarantee that the new delimiter will not already be somewhere in the text.
我想知道是否有让awk
以这种方式运行的选项
I want to know if there is an option to get awk
to behave this way
类似这样:
awk -F: '{print $1,$2}'
将打印:
one two:three:four:five:six seven:eight
我也想对$1
和$2
进行一些操作,所以我不想只替换第一次出现的:
.
I will also want to do some manipulations on $1
and $2
so I don't want just to substitute the first occurrence of :
.
推荐答案
无任何替换
echo "one:two:three:four:five" | awk -F: '{ st = index($0,":");print $1 " " substr($0,st+1)}'
index命令查找整个字符串中:"的第一次出现,因此在这种情况下,变量st将设置为4.然后,我使用substr函数从位置开始捕获字符串的所有其余部分. st + 1,如果没有提供结束号,它将转到字符串的末尾.输出为
The index command finds the first occurance of the ":" in the whole string, so in this case the variable st would be set to 4. I then use substr function to grab all the rest of the string from starting from position st+1, if no end number supplied it'll go to the end of the string. The output being
one two:three:four:five
如果要进行进一步处理,可以始终将字符串设置为变量以进行进一步处理.
If you want to do further processing you could always set the string to a variable for further processing.
rem = substr($0,st+1)
请注意,这已经在Solaris AWK上进行了测试,但是我看不出任何理由不能在其他版本上使用.
Note this was tested on Solaris AWK but I can't see any reason why this shouldn't work on other flavours.
这篇关于awk-仅按首次出现时进行拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!