Deleting parts of a Text

Asked

Viewed 80 times

5

Galera is the following wanted to be able to extract only the name of the user in a Shell SCRIPT but must be through the text I inform.

I exactly wanted to display on screen only: meucliente From the text: /home/meucliente/publlic_html

This is for a custom backup script that I’m putting together, basically I want to always delete the text /home/ and the text /public_html of any text I report, but I’m picking it up to get it.

3 answers

2

String Manipulation (Bash):

#!/bin/bash
txt='/home/meucliente/public_html'
aux=${txt%/*}
aux=${aux##*/}
echo $aux

Regular Expressions (Bash):

#!/bin/bash
txt='/home/meucliente/public_html'
[[ $txt =~ /([^/]+)/[^/]*$ ]]
echo "${BASH_REMATCH[1]}"

Using the awk:

#!/bin/bash
txt='/home/meucliente/public_html'
awk -F "/" '{ print $3 }' <<< $txt

Using the sed:

#!/bin/bash
txt='/home/meucliente/public_html'
sed 's,/[^/]\+/\([^/]\+\)/.*,\1,' <<< $txt

Using the cut:

#!/bin/bash
txt='/home/meucliente/public_html'
cut -d/ -f3 <<< $txt

Bash String Split Array:

#!/bin/bash
txt='/home/meucliente/public_html'
IFS='/' arr=( $txt )
echo "${arr[2]}"

1

You can do it this way:

#!/bin/bash
caminho='/home/meucliente/publlic_html'

from="/home/"
replace=""
caminho=${caminho//$from/$replace}

from="/publlic_html"
replace=""
caminho=${caminho//$from/$replace}

echo $caminho
  • 1

    My natural option was to play for the sed, but treat as variable expansion is much lighter

1

You can do it with cut:

echo "/home/meucliente/public_html" | cut -d'/' -f3
  • From what I understand, meucliente is a desired information. Your cut wouldn’t remove that?

  • 1

    @Jeffersonquesado No, only remove the chains of the first and third position, in this case: /home/ and /public_html. The cut -d'/' -f3 gets only the part after the second bar

  • True, I forgot the home bar

Browser other questions tagged

You are not signed in. Login or sign up in order to post.