Combining 2 different cut outputs in a single command?

I have a file such as the following:

1234
ABCD
EFGH

I’d like to convert it to the following:

2341
BCDA
FGHE

The actual file has 4,000 words, so I would like to do this in an efficient manner. I tried using the command cut -c 2-4,1 file.txt, but it produces the same exact output as the input. I was thinking I could use 3 different commands:

cut -c 1 file.txt > temp1.txt
cut -c 2-4 file.txt > temp2.txt
// combine the two with paste or pr

… but I would prefer a single command because I need to run it several times with slight modifications so running one command is less error prone than running 3 commands each time.

Is there any way to combine the 2 cut statements into one? Something like:

cut -c 1 file.txt | pr (cut -c 2-4 file.txt)

Or is there a better way to do this?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

With cut and paste you can also do an one-liner:

$ cat file
1234
ABCD
EFGH
$ paste --delimiter=''  <(cut file -c2-4) <(cut file -c1)
2341
BCDA
FGHE

Method 2

Using sed:

sed 's:^(.)(.*):21:' file.txt

2341
BCDA
FGHE

Method 3

If you use bash, use the string indexing of parameter expansion:

while IFS= read -r word; do
  echo "${word:1:3}${word:0:1}"
done < file.txt

Method 4

$ cat test
1234
ABCD
EFGH
$ awk -F "" '{print $2$3$4$1}' test
2341
BCDA
FGHE

You can change the separator via “-F” according to your data, and arrange the order of fields arbitrarily.

Method 5

Here’s one way with perl:

perl -F'' -lane 'print @F[<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c2d32325c5a">[email protected]</a>], $F[0]'

Auto-split at letter boundaries, rotate one to the left and print.

Method 6

I found an alternative in a script way:

~$ cut -c2- file.txt>file2.txt
~$ cut -c1 file.txt>file3.txt
~$ paste -d "" file2.txt file3.txt>file4.txt
~$ rm file2.txt file3.txt

The script cuts the chains in a separate files.
Then join into a new file (file4.txt)
And finally removes the spare files.

the llua solution is more clean for my taste.

Method 7

Have you tried rev ?

~$ cat filename | rev


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x