Pandya
Pandya

Reputation: 198

Formatting text and adding text-part between specific pattern

On GNU/Linux, I've following output by running ls command:

$ ls -l /dev/disk/by-label/
total 0
lrwxrwxrwx 1 root root 10 Mar  4 18:21 Documents+Edu -> ../../sda4
lrwxrwxrwx 1 root root 10 Mar  4 18:17 Ext4 -> ../../sda3
lrwxrwxrwx 1 root root 10 Mar  4 18:21 Game+Movie -> ../../sda6
lrwxrwxrwx 1 root root 10 Mar  4 18:42 OS -> ../../sda7
lrwxrwxrwx 1 root root 10 Mar  4 18:20 Software+Video -> ../../sda5

And I want the following output:

sudo mount /dev/sda4 /media/$USER/Documents+Edu
sudo mount /dev/sda3 /media/$USER/Ext4
sudo mount /dev/sda6 /media/$USER/Game+Movie
sudo mount /dev/sda7 /media/$USER/OS
sudo mount /dev/sda5 /media/$USER/Software+Video

In other words:-

How can I achieve desired output on Linux by using commands like: grep, cut, awk, sed, etc.?

Upvotes: 0

Views: 63

Answers (3)

jas
jas

Reputation: 10865

Another option could be to avoid ls altogether iterating through the files with readlink:

$ cat ../nols.sh
cd /dev/disk/by-label
for f in *
do
    v=$(basename $(readlink $f))
    echo "sudo mount /dev/$v /media/\$USER/$f"
done


$ sh ../nols.sh
sudo mount /dev/sda4 /media/$USER/Documents+Edu
sudo mount /dev/sda3 /media/$USER/Ext4
sudo mount /dev/sda6 /media/$USER/Game+Movie
sudo mount /dev/sda7 /media/$USER/OS
sudo mount /dev/sda5 /media/$USER/Software+Video

Upvotes: 1

NeronLeVelu
NeronLeVelu

Reputation: 10039

# -- Prepare ---
Folder='/dev/disk/by-label/'
HeaderLen=$(ls -ld . | wc -c )

# -- execute ---
ls -l "${Folder}" | sed "1d;s#.\{${HeaderLen}\}\(.*\) -> .*\(/[^/]*\)#sudo mount /dev\2 /media/\$USER/\1#;t;d"
  • estimate the first partof ls that is not used (and will be removed)
  • list the folder pipe to a sed
  • remove 1st line (total info)
  • remove first part and take 2 group of text separate by ->, rewrtie it in new format
  • if substitution occur, go to end of script (print)
  • if no, remove the line (and cycle without print). This remove file not linked in your format

Upvotes: 0

fedorqui
fedorqui

Reputation: 290235

Since you don't need anything apart from the names and its symbolic links, it might me best to just do ls -1 (one instead of L) ot just get the last column. Then, pipe to this awk:

awk -F"->|/" '{printf "sudo mount /dev/%s /media/$USER/%s\n", $NF, $1}'

It slices the text in either -> or / separators. Based on that, it gets the last one and the first one and populates the string accordingly.

Test

$ ls -1 /dev/disk/by-label/ | awk -F"->|/" '{printf "sudo mount /dev/%s /media/$USER/%s\n", $NF, $1}'
sudo mount /dev/sda4 /media/$USER/Documents+Edu 
sudo mount /dev/sda3 /media/$USER/Ext4 
sudo mount /dev/sda6 /media/$USER/Game+Movie 
sudo mount /dev/sda7 /media/$USER/OS 
sudo mount /dev/sda5 /media/$USER/Software+Video 

Upvotes: 1

Related Questions