简体   繁体   中英

how to restrict length of string present in a line using linux

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:

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.

In bash, you can use the following to limit the string, in this case, from index 0 to index 17.

$ var="this is a another string"

$ echo ${var:0:17}

this is a another

Using , by columns :

$ awk '{print $1, $2, $3, $4}' file

or with :

sed -r 's@^(\S+\s+\S+\s+\S+\s+\S+).*@\1@' file

or by length using :

$ cut -c 1-23 file

If you'd like to truncate strings on word boundaries, you could use fold with the -s option:

awk -F"\t" '{
    printf "%s\t", $1; system(sprintf("fold -sw 17 <<< \"%s\" | sed q", $2))
}'

The drawback is fold and sed need to be called for each line ( sed q is the same as tail -n1 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM