In this HackerRank Cut #1 problem solution we have Given N lines of input, print the 3rd character from each line as a new line of output. It is guaranteed that each of the n lines of input will have a 3rd character.

The cut command performs operations on each line it reads. It is often used for parsing data from log files, csv files, and similar. Given a firewall's log file, for example, cut and sort -u can be used to create a sorted list of unique ip addresses. Add in grep to get a strong tool for carving out data. The following lines show how to extract data from a line of text.

echo '0000 192.168.1.100 192.168.100.1' |cut -d ' ' -f 2

192.168.1.100

echo '0000 192.168.1.100 192.168.100.1' |cut -d ' ' -f 2 |cut -d '.' -f 4

100

echo '0000 192.168.1.100 192.168.100.1' |cut -d ' ' -f 2 |cut -d '.' -f 4|cut -c 1

1

The -d flag sets the delimiter, space in this case, and the -f flag shows which column to return, 2. The column count starts at 1.

In the next command, output from the first command is piped to a second command where the delimiter is a period and the column is 4. Finally, cut is used to extract the first character from the results of the second command.

HackerRank Cut #1 problem solution


Problem solution.

while read line
do
cut -c3 <<< "$line"
done


Second solution.

cut -c3