Hey there people on the internet. Here's my solution for Paste 2 Linux shell challenge from HackerRank. You can find answers to other Linux shell challenges via this link => https://blog.shasec.rocks/post/hackerrank-bash-challs. So let's get started. 

Challenge

In this challenge, we practice using the paste command to merge lines of a given file.

You are given a CSV file where each row contains the name of a city and its state separated by a comma. Your task is to restructure the file so that three consecutive rows are folded into one line and are separated by semicolons.

> Input Format

You are given a CSV file where each row contains the name of a city and its state separated by a comma.

> Output Format

Restructure the file so that three consecutive rows are folded into one line and are separated by semicolons.

> Sample Input

Albany, N.Y.
Albuquerque, N.M.
Anchorage, Alaska
Asheville, N.C.
Atlanta, Ga.
Atlantic City, N.J.
Austin, Texas
Baltimore, Md.
Baton Rouge, La.
Billings, Mont.
Birmingham, Ala.
Bismarck, N.D.
Boise, Idaho
Boston, Mass.
Bridgeport, Conn.

> Sample Output

Albany, N.Y.;Albuquerque, N.M.;Anchorage, Alaska
Asheville, N.C.;Atlanta, Ga.;Atlantic City, N.J.
Austin, Texas;Baltimore, Md.;Baton Rouge, La.
Billings, Mont.;Birmingham, Ala.;Bismarck, N.D.
Boise, Idaho;Boston, Mass.;Bridgeport, Conn.

> Explanation

The given input file has been reshaped as required.

Solution

I wrote a small script to get the job done. I've added some comments to make things more clear.

#!/bin/bash

counter=1
text=""

# Get input line by line inlcuding the last line
while read line || [ -n "$line" ]; do 

 if(( $counter >= 3 )); then
 # Add to input variable
 text+="${line}"

 # Use the paste command to what we did in the previous chall
 echo -e $(echo -e "${text}" | paste -s -d ';')

 # Reset the variables
 text=""
 counter=1

 # Back to top of the loop
 continue
 fi

 # Add to variables
 text+="${line}\n"
 counter=$((counter+1))

done
Blog Image
Figure 1.0: Solution passed all HackerRank tests cases

Below is the shorter solution with the paste command. Have a look at this answer from StackOverFlow which helped me get things working out.

#!/bin/bash

paste -d ';' - - -
Blog Image
Figure 1.1: Solution passed all HackerRank tests cases

If you like content like this, please consider buying me a coffee.

Thank you for your support :)


👇 Share this post 👇


💬 Comment Section 💬