How to use awk to print text string between characters

Written by
Date: 2020-06-14 17:35:32 00:00

Today while configuring my other blog to be hosted at vercel and moving it out from Apache, I had the need to create a redirect file from my htaccess file, so I needed first to print extract the file-names from a long string, the good thing was that the file-names were between a slash /.

These are the times when I love Linux, it has so many tools to achieve what you are looking for. This time I used awk

Let's see a simple example:

echo "/source/file/"|awk -F'[/|/]' '{print $2}'

The output will be:


And with this:

echo "/source/file/"|awk -F'[/|/]' '{print $3}'

The output will be:


So the command I used was:

cat file-with-strings | awk -F'[/|/]' '{print $3}' > new-file.txt

Then, to construct the new string (in case you are curious) awk comes again:

cat new-file.txt | awk '{print "{ \"source\": \"/en/blog/" $1 "\", \"destination\": \"/posts/" $1 "\", \"permanent\": true },"}'

The file new-file.txt had only the file-name part of the URI, and the output of the command above was:

{ "source": "/en/blog/why-i-have-a-blog.html", "destination": "/posts/why-i-have-a-blog.html", "permanent": true },