bash 如何使用linux限制一行中存在的字符串长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19869511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to restrict length of string present in a line using linux
提问by Jannat Arora
I have data of the following form:
我有以下形式的数据:
num1 This is a string
num2 This is another string
I want to limit length of all strings which are after the first tab..such that length(string)<4. Therefore, the output which I get is:
我想限制第一个选项卡之后的所有字符串的长度..这样长度(字符串)<4。因此,我得到的输出是:
num1 This is a string
num2 This is another
I can do this using python. But I am trying to find a linux equivalent in order to achieve the same.
我可以使用 python 来做到这一点。但我试图找到一个 linux 等价物以实现相同的目标。
回答by jramirez
In bash, you can use the following to limit the string, in this case, from index 0 to index 17.
在 bash 中,您可以使用以下内容来限制字符串,在这种情况下,从索引 0 到索引 17。
$ var="this is a another string"
$ echo ${var:0:17}
this is a another
回答by Gilles Quenot
回答by Cole Tierney
If you'd like to truncate strings on word boundaries, you could use fold
with the -s option:
如果您想在单词边界上截断字符串,可以使用fold
-s 选项:
awk -F"\t" '{
printf "%s\t", ; system(sprintf("fold -sw 17 <<< \"%s\" | sed q", ))
}'
The drawback is fold
and sed
need to be called for each line (sed q
is the same as tail -n1
).
缺点是fold
并且sed
需要为每一行调用(sed q
与 相同tail -n1
)。