Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sub and gsub function?

Tags:

substring

r

awk

I have this command:

$ find $PWD -name "*.jpg" | awk '{system( "echo "  $(sub(/\//, "_")) ) }'
_home/mol/Pulpit/test/1.jpg

Now the same thing, but using gsub:

$ find $PWD -name "*.jpg" | awk '{system( "echo "  $(gsub(/\//, "_")) ) }'

mol@mol:~

I want to get the result:

_home_mol_Pulpit_test_1.jpg

Thank you for your help.

EDIT:

I put 'echo' to test the command:

$ find $PWD -name "*.jpg" | awk '{gsub("/", "_")} {system( "echo " mv $0 " " $0) }'
_home_mol_Pulpit_test_1.jpg _home_pic_Pulpit_test_1.jpg

mol@mol:~

I want to get the result:

$ find $PWD -name "*.jpg" | awk '{gsub("/", "_")} {system( "echo " mv $0 " " $0) }'
/home/pic/Pulpit/test/1.jpg  _home_pic_Pulpit_test_1.jpg
like image 364
Tedee12345 Avatar asked Apr 29 '12 10:04

Tedee12345


People also ask

What is GSUB?

In Ruby, Gsub is a method that can be called on strings. It replaces all instances of a substring with another one inside the string. Sub is short for "substitute," and G stands for "global." Think of Gsub like a "replace all" function. The general pattern is str. gsub("target string", "replacement string").

What is GSUB in Rstudio?

The gsub() function in R can be used to replace all occurrences of certain text within a string in R. This function uses the following basic syntax: gsub(pattern, replacement, x) where: pattern: The pattern to look for. replacement: The replacement for the pattern.

What package is GSUB?

Description Generalized "gsub" and associated functions. gsubfn is an R package used for string matching, substitution and parsing.


1 Answers

That won't work if the string contains more than one match... try this:

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo "  $0) }'

or better (if the echo isn't a placeholder for something else):

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'

In your case you want to make a copy of the value before changing it:

echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'
like image 159
mata Avatar answered Oct 31 '22 18:10

mata