Swap Fields (strings) in a File – Unix / Linux

  • Updated
  • Posted in Programming
  • 1 min read

First we are going to see how you can swap two strings in a line after which we are going to see how you can swap two columns in a file.

As an instance, think about the textual content file with beneath information:

unix linux os
home windows mac os

Swap Strings utilizing Sed command:

Let see how you can swap the phrases unix and linux utilizing sed command in unix or linux surroundings. The sed command to swap the strings is proven beneath:

> sed 's/(unix) (linux)/2 1/' textfile
linux unix os
home windows mac os

The parentheses are used to recollect the sample. 1 signifies first sample and a couple of signifies second sample.

Swap Fields utilizing Awk command:

From the above file construction, we will observe that the file is in format of rows and columns the place the columns are delimited by area.

Awk command can be utilized to course of delimited information. Awk command to swap the primary two fields in a file is

> awk '{$0=$2." "$1" "$3; print $0}' textfile
linux unix os
mac home windows os

Another means utilizing awk is

awk '{print $2" "$1" "$3}' textfile

Leave a Reply