Friday 2 December 2016

Script to group together similar file names

In this post, I'd like to share a little script I wrote to club together similarly named contents in a file. The query was posted on social media & I'm sharing the same answer here which I wrote there.

So, here' s the problem statement:

Have a look at the below file testfile:

[root@centops ~]# cat testfile
test1.txt
test2.html
test4.sql
test3.txt
test4.txt
test5.sql
test7.html
test5.txt
test9.sql

The file contains names ending with txt, sql & html. What if I needed to group together the names ending with txt & similarly for sql & html. Here is a simple script which does exactly that:

[root@centops ~]# cat group.sh
#!/bin/bash

for i in $(< testfile)

do

##separate the file names into tmp files##

 r1=$(echo $i | grep txt$);  echo $r1 | sed '/^$/d' >> tmp1
 r2=$(echo $i | grep sql$);  echo $r2 | sed '/^$/d' >> tmp2
 r3=$(echo $i | grep html$); echo $r3  | sed '/^$/d' >> tmp3

done

##group the contents##

cat tmp1 tmp2 tmp3 >> result.txt

cat result.txt

rm -f tmp1 tmp2 tmp3


Here's the script output:

[root@centops ~]# ./group.sh
test1.txt
test3.txt
test4.txt
test5.txt
test4.sql
test5.sql
test9.sql
test2.html
test7.html


This particular script may cater to a very specific requirement but this is some food or thought. Through in a couple of variable to substitute the type of entities that need to be grouped & a parameter substitution for the file name & this little script may do a lot.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...