Mohamad Sholihin
Mohamad Sholihin

Reputation: 57

How to use awk or sed to get text between two words

I have string lists :

./SolutionController.php core/app/Http/Controllers/Admin/SolutionController.php
./ContentController.php core/app/Http/Controllers/Frontpage/ContentController.php
./country-flag vendor/country-flag

I wish I could get the final value between the './' sign and the 'space'

Output:

SolutionController.php
ContentController.php
country-flag

This code with bash script:

#!/bin/bash
tanggal=$(date +%d-%m-%Y)
filename="./update/$tanggal/lists.md"
n=1
tanggalWaktu=$(date +"%d-%m-%Y %H:%M:%S")
mkdir -p ./logs

while read line; do
    fileName=$(awk -F'[/ ]' '{print $2}' $line) 
    echo "file -> $fileName"
done < $filename

Output:

awk: can't open file ./SolutionController.php
 source line number 

Please help me

Upvotes: 1

Views: 77

Answers (2)

Akshay Hegde
Akshay Hegde

Reputation: 16997

Using awk :

awk -F'[/ ]' '{print $2}' string.txt 

Using gawk:

awk '{print gensub(/\.\/(.*) (.*)/,"\\1","g")}' string.txt

Test Results:

$ cat string.txt 
./SolutionController.php core/app/Http/Controllers/Admin/SolutionController.php
./ContentController.php core/app/Http/Controllers/Frontpage/ContentController.php
./country-flag vendor/country-flag  

$ awk -F'[/ ]' '{print $2}' string.txt 
SolutionController.php
ContentController.php
country-flag

$ awk '{print gensub(/\.\/(.*) (.*)/,"\\1","g")}' string.txt 
SolutionController.php
ContentController.php
country-flag

Upvotes: 2

logbasex
logbasex

Reputation: 2242

You can do it

echo "./SolutionController.php core/app/Http/Controllers/Admin/SolutionController.php" | sed -r 's/\.\/(.*) .*/\1/'

If you stored it in the file.

sed -r 's/\.\/(.*) .*/\1/' strings.txt

Upvotes: 0

Related Questions