Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a file with content as

123 OneTwoThree
234 TwoThreeFour
345 ThreeFourFive

I want to convert this file into something like this

OneTwoThree  123
TwoThreeFour  234
ThreeFourFive  345

Here the first column entries must get replaced at 25th place. If second column of original file have more letters that 25 then, rest letter must get skipped that means it should remove all characters after the 25th e.g. in above sample output file, 1 of first column is at 26th position.

Is it possible to do this with the help of awk, sed or any such command line tool ?

share|improve this question
    
When you say if it has more than 25 characters, the rest must be skipped, do you mean remove all characters after the 25th ? –  Jidder Aug 6 at 12:46
    
Yes..that's what I want –  SHW Aug 6 at 13:02
1  
Look at my answer :) –  Jidder Aug 6 at 13:05
    
-1 You say, “… e.g. in above sample output file …”, but your example doesn’t illustrate the point you’re trying to explain. Then, when somebody asks for clarification, you provide clarification in a comment. (You should edit your question to make it clear.) And then, given two answers, you accept the one that doesn’t answer your question, based on your clarification. –  Scott Aug 6 at 14:45
    
I was clueless for such answer...but the solution provided by Archemar was enough good to point me in right direction. Hence, I accepted the answer. Anyway, I'm editing the question :) –  SHW Aug 7 at 5:32

2 Answers 2

up vote 0 down vote accepted

If you want to truncate after the 25th character of the second field you can use the substr fuction in awk.

File

cat file
123 OneTwoThree
234 TwoThreeFour
345 ThreeFourFive
456 abcdefghijklmnopqrstuvwxyz

Output

awk '{printf("%-26s %s\n", substr($2,0,25),$1)}' file

OneTwoThree                123
TwoThreeFour               234
ThreeFourFive              345
abcdefghijklmnopqrstuvwxy  456
share|improve this answer

what about:

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

See:

cat file
123 OneTwoThree
234 TwoThreeFour
345 ThreeFourFive
789 abcdefghijklmnopqrstuvwxyz
999 abcdefghijklmnopqrstuvwxyzABC

Output:

awk '{printf "%-25s %s\n",$2,$1}' file
OneTwoThree               123
TwoThreeFour              234
ThreeFourFive             345
abcdefghijklmnopqrstuvwxyz 789
abcdefghijklmnopqrstuvwxyzABC 999
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.