E
E
ekaterina_cat2019-11-18 18:06:22
PowerShell
ekaterina_cat, 2019-11-18 18:06:22

How to leave only text inside desired fields?

Please tell me how to implement the following task: There is a large file with the following content

define( 'name', 'Name1' );
random text
define( 'surname', 'Surname1' );
random text
define( 'password', '111111111' );
random text
define( 'api', '123123123123123123' );
random text
random text
define( 'name', 'Name2' );
random text
define( 'surname', 'Surname2' );
random text
define( 'password', '777777777777' );
random text
define( 'api', '90909090909090' );

At the output you need to get:
Name1;Surname1;111111111;123123123123123123
Name2;Surname2;777777777777;90909090909090

How can this problem be solved? Thanks in advance!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
FanatPHP, 2019-11-18
@ekaterina_cat

I don’t know in the listed languages, I would solve such a problem in PHP

preg_match_all("!define\( '(.*?)', '(.*?)' \)!", $data, $m);
foreach ($m[2] as $i => $value) {
    echo $value;
    echo (($i + 1) % 4) ? ";" : "\n";
}

R
res2001, 2019-11-18
@res2001

batch file:

@echo off
SetLocal EnableDelayedExpansion

set "filename=1.txt"
set "name=" & set "surname=" & set "pass=" & set "api="
for /f "tokens=2,3 delims=(;', " %%a in ('findstr "define" %filename%') do (
  if /i "%%a" equ "name" (
    set "name=%%b"
  ) else if /i "%%a" equ "surname" (
    set "surname=%%b"
  ) else if /i "%%a" equ "password" (
    set "pass=%%b"
  ) else if /i "%%a" equ "api" (
    set "api=%%b"
  ) 
  if defined name if defined surname if defined pass if defined api (
    echo.!name!;!surname!;!password!;!api!
    set "name=" & set "surname=" & set "pass=" & set "api="
  )
)

It is assumed that the name, surname, password, api entries will be grouped exactly as in the example, i.e. records of different users will not be mixed.
In this case, problems are possible if the file contains data containing cmd special characters:!%&<>| ...

S
Saboteur, 2019-11-18
@saboteur_kiev

bash. In principle, you can still reduce ..

grep -Po "^define.*(name|surname|password|api)[', ]+\K[^']+" FILE.TXT|while read; do
  echo -n "$REPLY";
  count=$(($count+1))
  [ $count -gt 3 ]&&count=0&&echo ""||echo -n ";"
done
echo ""

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question