Deepti Jain
Deepti Jain

Reputation: 1921

Shell script to trim characters after a particular length from 1st word of every line

I am writing a shell script to do the following task. I have a file like this:

abcdfgfehg   124353552455
ldnaslbbdaj    134314314344
sdsdbbdbu    134134134314
auosdbo   141413434444
ihjidiqwdnowqdn  134134141232

I want the output file to be

abcdfgfeh 124353552455
ldnaslbbd 134314314344
sdsdbbdbu 134134134314
auosdbo   141413434444
ihjidiqwd 134134141232

That is, all the names (1st word in every line) should be reduced to 9 characters and remaining characters trimmed. A space after that. and then the value of the name.

I know that the awk command prints the 1st word of evry line.

awk '{print $1}' ./input.txt

But how to trim the characters from the file so that each word is of length 9 and its value start after a space.

Upvotes: 3

Views: 907

Answers (4)

potong
potong

Reputation: 58498

This might work for you:

sed 's/\S /&         /g;s/\(.\{9\}\)\S*\s*/\1 /' file
abcdfgfeh 124353552455
ldnaslbbd 134314314344
sdsdbbdbu 134134134314
auosdbo   141413434444
ihjidiqwd 134134141232

Upvotes: 0

user982733
user982733

Reputation:

You don't have to use the substring.

[srikanth@myhost ~]$ cat sample.txt
abcdfgfehg   124353552455
ldnaslbbdaj    134314314344
sdsdbbdbu    134134134314
auosdbo   141413434444
ihjidiqwdnowqdn  134134141232

[srikanth@myhost ~]$ awk '{ printf("%-.9s %s\n", $1, $2); }' sample.txt 
abcdfgfeh 124353552455
ldnaslbbd 134314314344
sdsdbbdbu 134134134314
auosdbo 141413434444
ihjidiqwd 134134141232

Please take a look @Jaypal's answer. You can handle width and precision with printf.

Upvotes: 0

Vijay
Vijay

Reputation: 67301

> awk '{print substr($1,1,9),$2}' temp
abcdfgfeh 124353552455
ldnaslbbd 134314314344
sdsdbbdbu 134134134314
auosdbo 141413434444
ihjidiqwd 134134141232

Upvotes: 0

jaypal singh
jaypal singh

Reputation: 77155

A simple printf would do -

awk '{printf ("%-10.9s%s\n", $1,$2)}' file

Test:

[jaypal:~/Temp] awk '{printf ("%-10.9s%s\n", $1,$2)}' file
abcdfgfeh 124353552455 
ldnaslbbd 134314314344
sdsdbbdbu 134134134314
auosdbo   141413434444
ihjidiqwd 134134141232

Test 2:

[jaypal:~/Temp] cat file
abcdfgfehg   1243535ABCD55
ldnaslbbdaj    134314314344
sdsdbbdbu    134134134314
auosdbo   141413434444
ihjidiqwdnowqdn  134134141232

[jaypal:~/Temp] awk '{printf ("%-10.9s%s\n", $1,$2)}' file
abcdfgfeh 1243535ABCD55
ldnaslbbd 134314314344
sdsdbbdbu 134134134314
auosdbo   141413434444
ihjidiqwd 134134141232

Upvotes: 1

Related Questions