Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Nth character with Sed

Tags:

string

sed

I'm in the middle of Playing Final Fantasy 7, and I'm at the part where you're in the Library at Shinra HQ and you have to write down the Nth letter--minus the spaces, where Nth is the number in front of the book's title--for every book that doesn't seem to belong in the current room, of which there are 4.

I need a sed script or other command-line to print the title of the book and get the Nth letter in its name.

like image 657
Alexej Magura Avatar asked Jul 26 '13 04:07

Alexej Magura


2 Answers

You don't need sed for that. You can use bash string substitution:

$ book="The Ancients in History"
$ book="${book// /}"   # Do global substition to remove spaces
$ echo "${book:13:1}"  # Start at position 13 indexed at 0 and print 1 character
H
like image 125
jaypal singh Avatar answered Sep 28 '22 18:09

jaypal singh


I figured out how to do it:

echo "The Ancients in History" | sed -r 's/\s//g ; s/^(.{13})(.).*$/\2/'

=> H

NOTE
Sed starts counting at 0 instead of 1, so if you want the 14th letter, ask for the 13th one.

Here's it in a shell script:

#!/bin/sh

if [[ -n "$1" ]]; then # string 

    if [[ -n "$2" ]]; then # Nth 

        echo "Getting character" $[$2 - 1]

        export Nth=$[$2 - 1]

        echo "$1" | sed -r "s/\s//g ; s/^(.{$Nth})(.).*$/\2/";
    fi
fi
like image 30
Alexej Magura Avatar answered Sep 28 '22 18:09

Alexej Magura